// 全局变量
let currentTab = 'dashboard';

// DOM 加载完成后执行
$(document).ready(function() {
    // 初始加载仪表盘数据
    loadDashboardData();

    // 绑定标签页切换事件
    bindTabEvents();

    // 绑定搜索事件
    bindSearchEvents();

    // 绑定表单提交事件
    bindFormEvents();
});

// 绑定标签页切换事件
function bindTabEvents() {
    $('.nav-item').click(function() {
        const tab = $(this).data('tab');
        if(!tab) return;

        currentTab = tab;
        $('.nav-item').removeClass('active');
        $(this).addClass('active');

        $('.content-section').hide();
        $(`#${tab}`).show();

        // 加载对应区域的数据
        loadTabData(tab);
    });
}

// 绑定搜索事件
function bindSearchEvents() {
    $('#userSearch').on('input', debounce(function() {
        searchUsers();
    }, 300));
}

// 绑定表单提交事件
function bindFormEvents() {
    $('#systemSettingsForm').submit(function(e) {
        e.preventDefault();
        saveSystemSettings();
    });
}

// 加载不同标签页的数据
function loadTabData(tab) {
    switch(tab) {
        case 'dashboard':
            loadDashboardData();
            break;
        case 'users':
            loadUsers();
            break;
        case 'rooms':
            loadRooms();
            break;
        case 'shop':
            loadShopItems();
            break;
        case 'system':
            loadSystemSettings();
            break;
    }
}

// 加载仪表盘数据
function loadDashboardData() {
    $.get('/api/admin/dashboard', function(data) {
        $('#onlineUsers').text(data.onlineUsers);
        $('#activeRooms').text(data.activeRooms);
        $('#todayRegisters').text(data.todayRegisters);
        $('#systemIncome').text(data.systemIncome);
    });
}

// 加载用户列表
function loadUsers() {
    $.get('/api/admin/users', function(users) {
        const tbody = $('#usersList');
        tbody.empty();

        users.forEach(user => {
            tbody.append(`
                <tr>
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>
                        <span class="score-value">${user.score}</span>
                        <button class="btn btn-sm btn-outline-primary ms-2" onclick="showScoreModal(${user.id})">
                            <i class="fas fa-edit"></i>
                        </button>
                    </td>
                    <td>${new Date(user.registerTime).toLocaleString()}</td>
                    <td>
                        <span class="badge ${user.status === 'ACTIVE' ? 'bg-success' : 'bg-danger'}">
                            ${user.status === 'ACTIVE' ? '正常' : '封禁'}
                        </span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <button class="btn btn-sm btn-warning" onclick="banUser(${user.id}, '${user.status}')">
                                ${user.status === 'ACTIVE' ? '封禁' : '解封'}
                            </button>
                            <button class="btn btn-sm btn-info" onclick="showResetPasswordModal(${user.id})">
                                重置密码
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">
                                删除
                            </button>
                        </div>
                    </td>
                </tr>
            `);
        });
    });
}

// 加载房间列表
function loadRooms() {
    $.get('/api/admin/rooms', function(rooms) {
        const tbody = $('#roomsList');
        tbody.empty();

        rooms.forEach(room => {
            tbody.append(`
                <tr>
                    <td>${room.id}</td>
                    <td>${room.owner}</td>
                    <td>${room.players.length}/3</td>
                    <td>
                        <span class="badge ${getBadgeClass(room.status)}">
                            ${getStatusText(room.status)}
                        </span>
                    </td>
                    <td>${new Date(room.createTime).toLocaleString()}</td>
                    <td>
                        <button class="btn btn-sm btn-danger btn-action" 
                                onclick="closeRoom(${room.id})"
                                ${room.status === 'CLOSED' ? 'disabled' : ''}>
                            关闭房间
                        </button>
                    </td>
                </tr>
            `);
        });
    });
}

// 加载商品列表
function loadShopItems() {
    $.get('/api/admin/shop/items', function(items) {
        const tbody = $('#shopItemsList');
        tbody.empty();

        items.forEach(item => {
            tbody.append(`
                <tr>
                    <td>${item.id}</td>
                    <td>
                        <img src="${item.imageUrl}" alt="${item.name}" 
                             style="width: 50px; height: 50px; object-fit: cover;">
                    </td>
                    <td>${item.name}</td>
                    <td>${item.description || '-'}</td>
                    <td>${item.price}</td>
                    <td>${getItemTypeText(item.type)}</td>
                    <td>
                        <span class="badge ${item.available ? 'bg-success' : 'bg-secondary'}">
                            ${item.available ? '上架' : '下架'}
                        </span>
                    </td>
                    <td>${new Date(item.createTime).toLocaleString()}</td>
                    <td>
                        <button class="btn btn-sm btn-primary btn-action" onclick="editItem(${item.id})">
                            编辑
                        </button>
                        <button class="btn btn-sm btn-danger btn-action" onclick="deleteItem(${item.id})">
                            删除
                        </button>
                    </td>
                </tr>
            `);
        });
    });
}

// 加载系统设置
function loadSystemSettings() {
    $.get('/api/admin/settings', function(settings) {
        $('#initialScore').val(settings.initialScore);
        $('#baseScore').val(settings.baseScore);
        $('#playTimeout').val(settings.playTimeout);
        $('#readyTimeout').val(settings.readyTimeout);
    });
}

// 用户管理相关函数
function banUser(userId, currentStatus) {
    const action = currentStatus === 'ACTIVE' ? '封禁' : '解封';
    if (confirm(`确定要${action}该用户吗？`)) {
        $.post(`/api/admin/users/${userId}/ban`)
            .done(function() {
                MessageUI.showMessage(`用户已${action}`, 'success');
                loadUsers();
            })
            .fail(function(error) {
                ErrorHandler.handleError(error, `${action}用户失败`);
            });
    }
}

function deleteUser(userId) {
    if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
        $.ajax({
            url: `/api/admin/users/${userId}`,
            method: 'DELETE',
            success: function() {
                MessageUI.showMessage('用户已删除', 'success');
                loadUsers();
            },
            error: function(error) {
                ErrorHandler.handleError(error, '删除用户失败');
            }
        });
    }
}

// 房间管理相关函数
function closeRoom(roomId) {
    if (confirm('确定要关闭该房间吗？')) {
        $.post(`/api/admin/rooms/${roomId}/close`)
            .done(function() {
                MessageUI.showMessage('房间已关闭', 'success');
                loadRooms();
            })
            .fail(function(error) {
                ErrorHandler.handleError(error, '关闭房间失败');
            });
    }
}

// 商品管理相关函数
function showAddItemModal() {
    $('#itemModalTitle').text('添加商品');
    $('#itemId').val('');
    $('#itemForm')[0].reset();
    $('#itemModal').modal('show');
}

function editItem(itemId) {
    $('#itemModalTitle').text('编辑商品');
    
    $.get(`/api/admin/shop/items/${itemId}`, function(item) {
        $('#itemId').val(item.id);
        $('#itemName').val(item.name);
        $('#itemDescription').val(item.description);
        $('#itemPrice').val(item.price);
        $('#itemImageUrl').val(item.imageUrl);
        $('#itemType').val(item.type);
        $('#itemStatus').val(item.available);
        $('#itemModal').modal('show');
    });
}

function saveItem() {
    const itemId = $('#itemId').val();
    const item = {
        name: $('#itemName').val(),
        description: $('#itemDescription').val(),
        price: parseInt($('#itemPrice').val()),
        imageUrl: $('#itemImageUrl').val(),
        type: $('#itemType').val(),
        available: $('#itemStatus').val() === 'true'
    };

    const url = itemId ? `/api/admin/shop/items/${itemId}` : '/api/admin/shop/items';
    const method = itemId ? 'PUT' : 'POST';

    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(item),
        success: function() {
            $('#itemModal').modal('hide');
            loadShopItems();
            MessageUI.showMessage(itemId ? '商品已更新' : '商品已添加', 'success');
        },
        error: function(error) {
            ErrorHandler.handleError(error, itemId ? '更新商品失败' : '添加商品失败');
        }
    });
}

function deleteItem(itemId) {
    if (confirm('确定要删除该商品吗？此操作不可恢复！')) {
        $.ajax({
            url: `/api/admin/shop/items/${itemId}`,
            method: 'DELETE',
            success: function() {
                loadShopItems();
                MessageUI.showMessage('商品已删除', 'success');
            },
            error: function(error) {
                ErrorHandler.handleError(error, '删除商品失败');
            }
        });
    }
}

// 系统设置相关函数
function saveSystemSettings() {
    const settings = {
        initialScore: $('#initialScore').val(),
        baseScore: $('#baseScore').val(),
        playTimeout: $('#playTimeout').val(),
        readyTimeout: $('#readyTimeout').val()
    };

    $.ajax({
        url: '/api/admin/settings',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(settings),
        success: function() {
            MessageUI.showMessage('设置已保存', 'success');
        },
        error: function(error) {
            ErrorHandler.handleError(error, '保存设置失败');
        }
    });
}

// 工具函数
function getBadgeClass(status) {
    switch(status) {
        case 'PLAYING': return 'bg-success';
        case 'WAITING': return 'bg-warning text-dark';
        case 'CLOSED': return 'bg-secondary';
        default: return 'bg-info';
    }
}

function getStatusText(status) {
    switch(status) {
        case 'PLAYING': return '游戏中';
        case 'WAITING': return '等待中';
        case 'CLOSED': return '已关闭';
        default: return status;
    }
}

function getItemTypeText(type) {
    switch(type) {
        case 'CARD_SKIN': return '卡牌皮肤';
        case 'CARD_BACK': return '卡牌背面';
        case 'AVATAR': return '头像';
        case 'AVATAR_FRAME': return '头像框';
        case 'EFFECT': return '特效';
        default: return type;
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 显示修改积分模态框
function showScoreModal(userId) {
    // 创建模态框
    const modal = $(`
        <div class="modal fade" id="scoreModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">修改用户积分</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="scoreForm">
                            <div class="mb-3">
                                <label class="form-label">积分变更</label>
                                <input type="number" class="form-control" id="scoreChange" required>
                                <small class="text-muted">正数为增加，负数为减少</small>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="updateScore(${userId})">保存</button>
                    </div>
                </div>
            </div>
        </div>
    `);

    // 添加到页面并显示
    $('body').append(modal);
    const modalInstance = new bootstrap.Modal(modal);
    modalInstance.show();

    // 模态框关闭时移除
    modal.on('hidden.bs.modal', function() {
        modal.remove();
    });
}

// 更新用户积分
function updateScore(userId) {
    const scoreChange = $('#scoreChange').val();

    $.ajax({
        url: `/api/admin/users/${userId}/update-score`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ scoreChange: parseInt(scoreChange) }),
        success: function() {
            $('#scoreModal').modal('hide');
            MessageUI.showMessage('积分已更新', 'success');
            loadUsers();
        },
        error: function(error) {
            ErrorHandler.handleError(error, '更新积分失败');
        }
    });
}

// 显示重置密码模态框
function showResetPasswordModal(userId) {
    // 创建模态框
    const modal = $(`
        <div class="modal fade" id="resetPasswordModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">重置用户密码</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="resetPasswordForm">
                            <div class="mb-3">
                                <label class="form-label">新密码</label>
                                <input type="password" class="form-control" id="newPassword" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">确认密码</label>
                                <input type="password" class="form-control" id="confirmPassword" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="resetPassword(${userId})">保存</button>
                    </div>
                </div>
            </div>
        </div>
    `);

    // 添加到页面并显示
    $('body').append(modal);
    const modalInstance = new bootstrap.Modal(modal);
    modalInstance.show();

    // 模态框关闭时移除
    modal.on('hidden.bs.modal', function() {
        modal.remove();
    });
}

// 重置用户密码
function resetPassword(userId) {
    const newPassword = $('#newPassword').val();
    const confirmPassword = $('#confirmPassword').val();

    if (newPassword !== confirmPassword) {
        MessageUI.showMessage('两次输入的密码不一致', 'error');
        return;
    }

    $.ajax({
        url: `/api/admin/users/${userId}/reset-password`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ newPassword: newPassword }),
        success: function() {
            $('#resetPasswordModal').modal('hide');
            MessageUI.showMessage('密码已重置', 'success');
        },
        error: function(error) {
            ErrorHandler.handleError(error, '重置密失败');
        }
    });
}

// 图片上传函数
function uploadImage() {
    const fileInput = $('#itemImageFile')[0];
    if (!fileInput.files || !fileInput.files[0]) {
        MessageUI.showMessage('选择要上传的图片', 'warning');
        return;
    }

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);

    $.ajax({
        url: '/api/admin/shop/upload',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            $('#itemImageUrl').val(response.url);
            $('#imagePreview').show().find('img').attr('src', response.url);
            MessageUI.showMessage('图片上传成功', 'success');
        },
        error: function(error) {
            ErrorHandler.handleError(error, '图片上传失败');
        }
    });
}

// 修改图片预览功能
$('#itemImageFile').change(function() {
    const file = this.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            $('#imagePreview').show().find('img').attr('src', e.target.result);
        };
        reader.readAsDataURL(file);
    }
});